package com.donleo.security.controller;

import com.donleo.common.api.CommonResult;
import com.donleo.common.relation.UserRoleRelation;
import com.donleo.security.model.User;
import com.donleo.security.service.UserRoleRelationService;
import com.donleo.security.service.UserService;
import com.donleo.security.utils.JwtTokenUtil;
import com.donleo.security.vo.LoginParams;
import com.donleo.security.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @author liangd
 * @since 2021-01-16 9:34
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserRoleRelationService userRoleRelationService;

    /**
     * Authorization
     */
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginParams loginParams, HttpServletRequest request) {
        HashMap<String, String> data = new HashMap<>();
        boolean b = userService.isValidateCode(loginParams.getValidateCode());
        if (b) {
            return CommonResult.failed("验证码错误");
        }
        //判断账户是否被冻结
        boolean b1 = userService.isFrozenUser(loginParams.getCode());
        if (b1) {
            return CommonResult.frozenFailed();
        }
        String token = null;
        try {
            token = userService.login(loginParams);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.validateFailed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        data.put("tokenHead", tokenHead);
        data.put("token", token);
        data.put("code", loginParams.getCode());
        return CommonResult.success(data);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody User user) {
        boolean b = userService.register(user);
        if (b) {
            return CommonResult.success("注册成功");
        }
        return CommonResult.failed("账号已存在");
    }

    /**
     * 判断是否有访问路径的权限
     */
    @PostMapping("/checkAuth")
    public CommonResult checkAuth(@RequestParam String userCode, @RequestParam String uri) {
        return userService.checkAuth(userCode, uri);
    }

    /**
     * 更新
     */
    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        Assert.notNull(user.getId(), "Id is not to be null");
        return userService.updateUser(user);
    }

    /**
     * 查询单个
     */
    @GetMapping("/findById")
    public CommonResult findById(Integer id) {
        User user = userService.findById(id);
        return CommonResult.success(user);
    }


    /**
     * 查询所有
     */
    @GetMapping("/findAll")
    public CommonResult findAll(UserVo userVo) {
        List<User> list = userService.findAll(userVo);
        long total = userService.getCount(userVo);
        return CommonResult.success(total, list);
    }

    /**
     * 根据用户编号查
     */
    @GetMapping("/findByCode")
    public CommonResult findByCode(String code) {
        User user = userService.getUserByCode(code);
        return CommonResult.success(user);
    }

    /**
     * 根据用户编号获取用户名
     */
    @GetMapping("/getUserNameByCode")
    public CommonResult getUserCodeByCode(String code){
        return userService.getUserNameByCode(code);
    }

    /**
     * 分配角色
     */
    @PostMapping("/distributeRole")
    public CommonResult distributeRole(@RequestBody UserRoleRelation userRoleRelation) {
        return userRoleRelationService.distributeRole(userRoleRelation);
    }


    /**
     * 根据角色编号查用户
     */
    @GetMapping("/findUserByRoleCode")
    public CommonResult findUserByRoleCode(String roleCode) {
        List<User> list = userService.findUserByRoleCode(roleCode);
        return CommonResult.success(list);
    }

    /**
     * 根据小组编号查询用户
     */
    @GetMapping("/findUserByTeamCode")
    public CommonResult findUserByTeamCode(Integer pageNum, Integer pageSize, String teamCode) {
        List<User> list = userService.findUserByTeamCode(teamCode, pageNum, pageSize);
        long total = userService.getCountByTeamCode(teamCode);
        return CommonResult.success(total, list);
    }

    /**
     * 查询未分组的用户
     */
    @GetMapping("/findUngroupedUser")
    public CommonResult findUngroupedUser() {
        List<User> list = userService.findUngroupedUser();
        return CommonResult.success(list);
    }

    /**
     * 根据token获取当前登录用户
     */
    @GetMapping("/getLoginUser")
    public CommonResult getLoginUser(HttpServletRequest request) {
        String authHeader = request.getHeader(this.tokenHeader);
        User user = new User();
        if (authHeader != null) {
            boolean b1 = StringUtils.startsWithIgnoreCase(authHeader, this.tokenHead);
            if (b1) {
                String authToken = authHeader.substring(this.tokenHead.length()).trim();
                String userCode = jwtTokenUtil.getUserCodeFromToken(authToken);
                user = userService.getUserByCode(userCode);
            }
        }
        return CommonResult.success(user);
    }
}
